import $ from "jquery";
import JSSM4 from "jssm4";
import service from "./req";
// const baseUrl = "https://www.zwfw.hlj.gov.cn";
const signUrl =
  "https://www.zwfw.hlj.gov.cn/jpaas-jags-server/interface/createsign.do"; //签名接口地址
const gatewayUrl =
  "https://www.zwfw.hlj.gov.cn/jpaas-jags-server/interface/gateway.do"; //网关接口地址

// sm4加密
const sm4Encrypt = (text) => {
  let sm4 = new JSSM4("8c82deb5c3fb4a3d");
  return sm4.encryptData_ECB(text);
};

// sm4解密
const sm4Decrypt = (text) => {
  let sm4 = new JSSM4("8c82deb5c3fb4a3d");
  return sm4.decryptData_ECB(text);
};
const getRequest = (name) => {
  return (
    decodeURIComponent(
      (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
        location.href
      ) || [, ""])[1].replace(/\+/g, "%20")
    ) || null
  );
};

function isAlipay() {
  let ua = navigator.userAgent.toLowerCase();
  if (ua.match(/Alipay/i) == "alipay") {
    return true;
  } else {
    return false;
  }
}

function isWx() {
  let ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  }
}


const getUser = () => {

  return new Promise((resolve, reject) => {
    if (isWx() || isAlipay()) {
      sessionStorage.setItem("userId", getRequest("userId"));
      service
        .requestJMAS({
          interface_id: "getMoreTicket",
          app_id: "hljuser",
          params: {
            ticket: getRequest("ticket"),
            userId: getRequest("userId"),
          },
        })
        .then((res) => {
          console.log(res, "获取票据");
          if (res.data.code == 200) {
            let ticketNew = JSON.parse(JSON.parse(res.data.data).data).ticket;

            console.log(ticketNew, "新票据");
            sessionStorage.setItem("ticketNew", ticketNew);
            let queryParams = {
              ticket: ticketNew,
            };
            let datestr = new Date().valueOf();
            let param = {
              app_id: "hljuser",
              interface_id: "getUserInfoByTicket",
              version: "1.0",
              biz_content: JSON.stringify(queryParams),
              charset: "utf-8",
              timestamp: datestr,
              origin: "1",
            };
            $.ajax({
              type: "post",
              url: signUrl,
              data: param,
              timeout: 3000,
              success: (res) => {
                param.sign = res.data.sign;
                $.ajax({
                  type: "post",
                  url: gatewayUrl,
                  data: param,
                  timeout: 3000,
                  success: (res) => {
                    // console.log(res);
                    let resp = JSON.parse(res.data).data;

                    let userInfo = sm4Decrypt(resp);
                    console.log(userInfo, "2222222222222");
                    sessionStorage.setItem(
                      "ticketNew",
                      JSON.parse(userInfo).ticket
                    );
                    // console.log(JSON.parse(userInfo).userinfo,'&&&&&');
                    resolve(JSON.parse(userInfo).userinfo);
                  },
                  error: (err) => {
                    reject(err);
                  },
                });
              },
              error: (err) => {
                reject(err);
              },
            });
          }
        });
    } else {
      lightAppJssdk.user.getTicket({
        success: (data) => {
          if (data == "未登录") {
            console.log("未登录1");
            let res = onLoginApp();
            resolve(res);
          } else {
            let oldTicket = data;
            if (sessionStorage.getItem("ticketNew")) {
              oldTicket = sessionStorage.getItem("ticketNew");
              console.log("这是存ticktnew的if判断");


            }
            if (getRequest("userId") || sessionStorage.getItem("ticketNew")) {
              sessionStorage.setItem("userId", getRequest("userId"));
              service
                .requestJMAS({
                  interface_id: "getMoreTicket",
                  app_id: "hljuser",
                  params: {
                    ticket: oldTicket,
                    userId: getRequest("userId"),
                  },
                })
                .then((res) => {
                  console.log(res, "获取票据");
                  if (res.data.code == 200) {
                    let ticketNew = JSON.parse(
                      JSON.parse(res.data.data).data
                    ).ticket;
                    oldTicket = ticketNew;
                    console.log(ticketNew, "新票据");
                    sessionStorage.setItem("ticketNew", ticketNew);
                    let queryParams = {
                      ticket: oldTicket,
                    };
                    let datestr = new Date().valueOf();
                    let param = {
                      app_id: "hljuser",
                      interface_id: "getUserInfoByTicket",
                      version: "1.0",
                      biz_content: JSON.stringify(queryParams),
                      charset: "utf-8",
                      timestamp: datestr,
                      origin: "1",
                    };
                    $.ajax({
                      type: "post",
                      url: signUrl,
                      data: param,
                      timeout: 3000,
                      success: (res) => {
                        param.sign = res.data.sign;
                        $.ajax({
                          type: "post",
                          url: gatewayUrl,
                          data: param,
                          timeout: 3000,
                          success: (res) => {
                            console.log("成功1");
                            // console.log(res);
                            let resp = JSON.parse(res.data).data;

                            let userInfo = sm4Decrypt(resp);
                            alert(userInfo)
                            $.ajax({
                              type: "get",
                              url: "https://jmsztc.jmsdata.org.cn/business/in?ticket=" + JSON.parse(userInfo).ticket,
                              timeout: 3000,
                              success: (res) => {
                                window.localStorage.setItem("token", res);
                                console.log("获取token1",token);

                              }
                            })
                            sessionStorage.setItem(
                              "ticketNew",
                              JSON.parse(userInfo).ticket
                            );
                            // console.log(JSON.parse(userInfo).userinfo,'&&&&&');
                            resolve(JSON.parse(userInfo).userinfo);
                          },
                          error: (err) => {
                            reject(err);
                          },
                        });
                      },
                      error: (err) => {
                        reject(err);
                      },
                    });
                  }
                });
            } else {
              let queryParams = {
                ticket: oldTicket,
              };
              let datestr = new Date().valueOf();
              let param = {
                app_id: "hljuser",
                interface_id: "getUserInfoByTicket",
                version: "1.0",
                biz_content: JSON.stringify(queryParams),
                charset: "utf-8",
                timestamp: datestr,
                origin: "1",
              };
              $.ajax({
                type: "post",
                url: signUrl,
                data: param,
                timeout: 3000,
                success: (res) => {
                  param.sign = res.data.sign;
                  $.ajax({
                    type: "post",
                    url: gatewayUrl,
                    data: param,
                    timeout: 3000,
                    success: (res) => {
                      // console.log(res);
                      let resp = JSON.parse(res.data).data;
                      // console.log(resp,'2222222222222');
                      let userInfo = sm4Decrypt(resp);
                      console.log("成功2");

                      $.ajax({
                        type: "get",
                        url: "https://jmsztc.jmsdata.org.cn/business/in?ticket=" + JSON.parse(userInfo).ticket,
                        timeout: 3000,
                        async:false,
                        success: (res) => {
                          window.localStorage.setItem("token", res);
                          console.log("获取token1",token);

                        }
                      })
                      sessionStorage.setItem(
                        "ticketNew",
                        JSON.parse(userInfo).ticket
                      );
                      resolve(JSON.parse(userInfo).userinfo);
                    },
                    error: (err) => {
                      reject(err);
                    },
                  });
                },
                error: (err) => {
                  reject(err);
                },
              });
            }
            //返回ticket给到h5,调用统一身份认证根据ticket获取用户信息接口
          }
        },
      });
    }
  });
};
const getNewTicket = (url) => {
  let oldTicket = sessionStorage.getItem("ticketNew");
  let userId = getRequest("userId");
  service
    .requestJMAS({
      interface_id: "getMoreTicket",
      app_id: "hljuser",
      params: {
        ticket: oldTicket,
        userId: userId,
      },
    })
    .then((res) => {
      if (res.data.code == 200) {
        let ticketNew = JSON.parse(JSON.parse(res.data.data).data).ticket;
        sessionStorage.setItem("ticketNew", ticketNew);
        if (url.indexOf("?") != -1) {
          url = url + `&ticket=${oldTicket}&userId=${userId}`;
        } else {
          url = url + `?ticket=${oldTicket}&userId=${userId}`;
        }
        window.location.href = url;
      }
    });
};
// 拉起app登陆界面
const onLoginApp = () => {
  return new Promise((resolve, reject) => {
    lightAppJssdk.user.loginapp({
      success: function (data) {
        if (data == "未登录") {
          //取消登录或登录失败，关闭页面
          oncloseWindow();
        } else {
          //返回ticket给到h5,调用根据ticket获取用户信息接口
          let queryParams = {
            ticket: data,
          };
          let datestr = new Date().valueOf();
          let param = {
            app_id: "hljuser",
            interface_id: "getUserInfoByTicket",
            version: "1.0",
            biz_content: JSON.stringify(queryParams),
            charset: "utf-8",
            timestamp: datestr,
            origin: "1",
          };
          $.ajax({
            type: "post",
            url: signUrl,
            data: param,
            timeout: 3000,
            success: (res) => {
              param.sign = res.data.sign;
              $.ajax({
                type: "post",
                url: gatewayUrl,
                data: param,
                timeout: 3000,
                success: (res) => {
                  // console.log(res);
                  let resp = JSON.parse(res.data).data;
                  // console.log(resp,'11111111111');
                  let userInfo = sm4Decrypt(resp);
                  // console.log(JSON.parse(userInfo).userinfo,'1111111');
                  resolve(JSON.parse(userInfo).userinfo);
                },
                error: (err) => {
                  reject(err);
                },
              });
            },
            error: (err) => {
              reject(err);
            },
          });
        }
      },
      fail: function (data) {
        //关闭页面
        oncloseWindow();
      },
    });
  });
};
/**
 * 关闭容器
 */
const oncloseWindow = () => {
  lightAppJssdk.navigation.close({
    success: function (data) { },
    fail: function (data) { },
  });
};

export default { getUser };
